package api

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/ChuranNeko/gginx/internal/config"
)

type APIServer struct {
	conf *config.Config
	mux  *http.ServeMux
}

func NewAPIServer(conf *config.Config) *APIServer {
	s := &APIServer{
		conf: conf,
		mux:  http.NewServeMux(),
	}
	s.setupRoutes()
	return s
}

func (s *APIServer) setupRoutes() {
	s.mux.HandleFunc("/api/config", s.handleConfig)
	s.mux.HandleFunc("/api/backends", s.handleBackends)
}

func (s *APIServer) Start() error {
	if !s.conf.API.Enabled {
		return nil
	}
	addr := s.conf.API.ListenAddr
	if addr == "" {
		addr = fmt.Sprintf(":%d", s.conf.API.Port)
	}
	return http.ListenAndServe(addr, s.mux)
}

func (s *APIServer) handleConfig(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	json.NewEncoder(w).Encode(s.conf)
}

func (s *APIServer) handleBackends(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		json.NewEncoder(w).Encode(s.conf.Backends)

	case http.MethodPost:
		var backend config.Backend
		if err := json.NewDecoder(r.Body).Decode(&backend); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		s.conf.Backends = append(s.conf.Backends, backend)
		w.WriteHeader(http.StatusCreated)
		json.NewEncoder(w).Encode(backend)

	case http.MethodDelete:
		url := r.URL.Query().Get("url")
		if url == "" {
			http.Error(w, "Missing url parameter", http.StatusBadRequest)
			return
		}

		var newBackends []config.Backend
		for _, b := range s.conf.Backends {
			if b.URL != url {
				newBackends = append(newBackends, b)
			}
		}
		s.conf.Backends = newBackends
		w.WriteHeader(http.StatusNoContent)

	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}
